package com.xinzhi.savingpot.search.service.impl;


import com.xinzhi.savingpot.search.service.ITaskInfoSolrService;
import com.xinzhi.savingpot.search.vo.TaskInfoSolr;
import com.xinzhi.savingpot.task.entity.TaskInfo;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TaskInfoSolrServiceImpl implements ITaskInfoSolrService {
    @Autowired
    private SolrClient solrClient;


    @Override
    public List<TaskInfoSolr> queryAll() {
        // 定义查询条件
        List<TaskInfoSolr> products = new ArrayList<TaskInfoSolr>();
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q","*:*");
        //每页显示行数
        solrQuery.setStart(0);
        solrQuery.setRows(15);
        solrQuery.addSort("task_taskUnitPrice",SolrQuery.ORDER.asc);
        try {
            // 执行查询
            QueryResponse query = solrClient.query(solrQuery);
            // 获取结果集
            SolrDocumentList results = query.getResults();
            for (SolrDocument s: results) {
                TaskInfoSolr taskInfoSolr = new TaskInfoSolr();
                taskInfoSolr.setTaskId( s.getFieldValues("id").toString());
                taskInfoSolr.setTaskClassId(s.getFieldValue("task_taskClassId").toString());
                taskInfoSolr.setUserId(s.getFieldValue("task_userId").toString());
                taskInfoSolr.setTaskTitle(s.getFieldValue("task_taskTitle").toString());
                taskInfoSolr.setTaskNumber( s.getFieldValue("task_taskNumber").toString());
                taskInfoSolr.setTaskUnitPrice((Double)s.getFieldValue("task_taskUnitPrice"));
                taskInfoSolr.setReleaseTime( s.getFieldValue("task_releaseTime").toString());
                products.add(taskInfoSolr);
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return products;
    }


    @Override
    public List<TaskInfoSolr> searchGoodsByKeyword(String keyword) {
        SolrQuery solrQuery=new SolrQuery();
        if (keyword==null){
            //搜索全部商品
            solrQuery.setQuery("*:*");
        }else{
            //根据条件搜索(注意多条件连接时，之间要有空格)
            solrQuery.setQuery("task_taskNumber:"+keyword+" || task_taskTitle:"+keyword);
        }
        //设置高亮
        solrQuery.setHighlight(true);
        //添加需要高亮的字段
        solrQuery.addHighlightField("task_taskNumber");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        try {
            QueryResponse results = solrClient.query(solrQuery);
            //获得高亮的结果
            //Map<id,Map<Field,List<String>>>
            //id:有高亮的商品id    Field:当前商品有高亮的字段   List:高亮的内容
            Map<String, Map<String, List<String>>> highlighting = results.getHighlighting();
            SolrDocumentList documents = results.getResults();
            List<TaskInfoSolr> taskInfoSolrList=new ArrayList<>();

            for (SolrDocument document:documents) {
                TaskInfoSolr taskInfoSolr = new TaskInfoSolr();
                taskInfoSolr.setTaskId(document.get("id")+"");
                taskInfoSolr.setUserId(document.get("task_userId")+"");
                taskInfoSolr.setTaskClassId(document.get("task_taskClassId")+"");
                taskInfoSolr.setTaskNumber((document.get("task_taskNumber")+""));
                taskInfoSolr.setTaskTitle(document.get("task_taskTitle")+"");
                taskInfoSolr.setTaskUnitPrice((Double.parseDouble(document.get("task_taskUnitPrice")+"")));
                taskInfoSolr.setReleaseTime(document.get("task_releaseTime")+"");
                //判断当前商品是否有高亮     根据商品id进行判断
                if (highlighting.containsKey(taskInfoSolr.getTaskId()+"")){

                    //获取有高亮的内容
                    Map<String, List<String>> map = highlighting.get(taskInfoSolr.getTaskId() + "");
                    System.out.println(map.toString());
                    //获取高亮的内容
                    String name = map.get("task_taskNumber").get(0);
                    //将高亮的内容替换到对象中
                    taskInfoSolr.setTaskNumber(name);
                }
                taskInfoSolrList.add(taskInfoSolr);
            }
            return taskInfoSolrList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    @Override
//    public List<String> querySuggest(String query) {
//        SolrQuery solrQuery = new SolrQuery();
//        //建议查询
//        solrQuery.setRequestHandler("/suggest");
//        solrQuery.set("suggest.build", true);
//        solrQuery.set("suggest.dictionary", "suggest");
//        solrQuery.set("q", query);
//
//        QueryResponse queryResponse = null;
//        try {
//            solrClient.commit("mycore");
//            queryResponse = solrClient.query("mycore",solrQuery);
//        } catch (SolrServerException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        List<String> result = new ArrayList<String>();
//        if (queryResponse != null) {
//            NamedList namedList = queryResponse.getResponse();
//            Map map = (Map) namedList.get("suggest");
//            NamedList dictionaryMap = (NamedList) map.get("suggest");
//            NamedList data = (NamedList) dictionaryMap.get(query);
//            Integer numFound = Integer.valueOf(data.get("numFound").toString());
//            List<NamedList> suggests = (List<NamedList>) data.get("suggestions");
//            for (int i = 0; i < suggests.size(); i++) {
//                result.add(suggests.get(i).get("prod_pname").toString());
//            }
//
//        }
//        return result;
//
//    }

//    @Override
//    public void delete(String id) {
//        try {
//            solrClient.deleteById("mycore",id);
//            solrClient.commit("mycore");
//        } catch (SolrServerException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
